package com.jron.cqiu.kernel.implement.windows.winp;

import com.jron.cqiu.kernel.process.IProcess;
import org.jvnet.winp.WinProcess;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-13
 * @Time: 11:12:08
 */
public class WinpProcess implements IProcess {

    private static Log log = LogFactory.getLog(WinpProcess.class);

    /**
     * 结束进程
     *
     * @param moduleBaseName
     * @param ignoreCase     映像名称是否忽略大小写
     * @return
     */
    public int kill(String moduleBaseName, boolean ignoreCase) {
        String mbname = null;
        String cmd = null;
        WinProcess.enableDebugPrivilege();
        for (WinProcess p : WinProcess.all()) {
            if (p.getPid() < 10) continue;

            cmd = p.getCommandLine();
            mbname = StringUtils.remove(StringUtils.substringAfterLast(cmd, "\\"), "\"").trim();
            log.debug("moduleBaseName: " + mbname + "\t\t\t, CommandLine: " + cmd);

            if ((ignoreCase ? mbname.equalsIgnoreCase(moduleBaseName) : mbname.equals(moduleBaseName))) {
                p.killRecursively();
                log.debug("Found and killed the: " + mbname);
                break;
            }
        }
        return 0;
    }

    /**
     * 结束进程 默认忽略映像名称大小写
     *
     * @param moduleBaseName
     * @return
     */
    public int kill(String moduleBaseName) {
        return kill(moduleBaseName, true);
    }

    /**
     * 根据PID结束进程
     *
     * @param moduleBaseName
     * @return
     */
    public int kill(int pid) {
        log.debug("The pid is: " + pid);
        WinProcess.enableDebugPrivilege();
        new WinProcess(pid).killRecursively();
        return 0;
    }
}
